package c.c.k.service.impl;

import c.c.k.config.StockConfig;
import c.c.k.pojo.Fund;
import c.c.k.pojo.FundBase;
import c.c.k.repository.FundBaseRepository;
import c.c.k.repository.FundRepository;
import c.c.k.service.FundBaseService;
import c.c.k.service.FundService;
import c.c.k.util.StockUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by chenck on 2022/3/19.
 */
@Service
@Slf4j
public class FundBaseServiceImpl implements FundBaseService {
    @Autowired
    private FundBaseRepository fundBaseRepository;
    @Autowired
    private StockConfig stockConfig;

    @Override
    public void initFundBase() {
        StockUtil.parseJsonArray(stockConfig.getFundUrl(), jsonArray -> {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String mc = jsonObject.getStr("mc");
                String dm = jsonObject.getStr("dm");

                FundBase byCode = fundBaseRepository.findByCode(dm);
                if(byCode == null){
                    byCode = FundBase.builder().code(dm).name(mc).build();
                    fundBaseRepository.save(byCode);
                }
            }
        });
    }

    @Override
    public FundBase getFundBase(Long id) {
        return fundBaseRepository.getOne(id);
    }

    @Override
    public List<FundBase> listAll(List<Long> ids) {
        return fundBaseRepository.findAllById(ids);
    }
}
